from django.shortcuts import render
from .binary_classifier import BinaryClassifier
from .categorical_classifier import CategoricalClassifier
from .deep_learning_regressor import DeepLearningRegressor
from .lstm_timeseries import LSTMTimeseries
from .image_recognition import ImageRecognition
import re
from BigDataWeb.view import get_algorithm
from BigDataWeb.view import put_algorithm
from BigDataWeb.view import read_data_source


def binary_classifier(request):
    context = {}
    algorithm = BinaryClassifier()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "deep_learning/1.html", context)


def categorical_classifier(request):
    context = {}
    algorithm = CategoricalClassifier()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "deep_learning/1.html", context)


def deep_learning_regressor(request):
    context = {}
    algorithm = DeepLearningRegressor()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "deep_learning/1.html", context)


def lstm_timeseries(request):
    context = {}
    algorithm = LSTMTimeseries()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "deep_learning/1.html", context)


def image_recognition(request):
    context = {}
    algorithm = ImageRecognition()
    algorithm.user_id = request.session["login_name"]
    put_algorithm(algorithm)
    context["algorithm"] = algorithm
    return render(request, "deep_learning/1.html", context)


def select_data_source(request):
    context = {}
    algorithm = get_algorithm(request)
    read_data_source(request, algorithm)
    context["algorithm"] = algorithm
    if algorithm.algorithm_name == "深度学习-图像识别":
        algorithm.implent()
        algorithm.generateNotebookFile()
        return render(request, "deep_learning/5.html", context)
    else:
        return render(request, "deep_learning/2.html", context)


def understand_data_set(request):
    context = {}
    algorithm = get_algorithm(request)
    if algorithm.algorithm_name == "深度学习-LSTM":
        algorithm.setInOutPutFieldName(request.POST.get("in_out_put_field_name"))
    else:
        algorithm.setInPutFieldName(request.POST.getlist("input_field_names"))
        algorithm.setOutPutFieldName(request.POST.get("output_field_name"))
        algorithm.hidden_layer_count = int(request.POST.get("hidden_layer_count"))
        algorithm.hidden_layer_units = [8] * algorithm.hidden_layer_count
    context["algorithm"] = algorithm
    return render(request, "deep_learning/3.html", context)


def configure_parameters(request):
    context = {}
    algorithm = get_algorithm(request)
    context["algorithm"] = algorithm
    if algorithm.algorithm_name == "深度学习-二分类" or algorithm.algorithm_name == "深度学习-多分类" or algorithm.algorithm_name == "深度学习-回归":
        algorithm.hidden_layer_units = [int(x) for x in request.POST.getlist("hidden_layer_units")]
        algorithm.epochs = int(request.POST.get("epochs"))
        algorithm.batch_size = int(request.POST.get("batch_size"))
        algorithm.optimizer = request.POST.get("optimizer")
        algorithm.train_size = float(request.POST.get("train_size")) * 0.01
        algorithm.test_size = float(request.POST.get("test_size")) * 0.01
        return render(request, "deep_learning/4.html", context)
    elif algorithm.algorithm_name == "深度学习-LSTM":
        algorithm.look_back = int(request.POST.get("look_back"))
        algorithm.epochs = int(request.POST.get("epochs"))
        algorithm.train_ratio = float(request.POST.get("train_ratio")) * 0.01
        algorithm.lstm_units = int(request.POST.get("lstm_units"))
        algorithm.implent()
        algorithm.generateNotebookFile()
        return render(request, "deep_learning/5.html", context)


def upload_predict_input_values(request):
    context = {}
    algorithm = get_algorithm(request)
    algorithm.predict_input_values = []
    for line in request.POST.get("predict_input_values").split("\n"):
        line = line.strip()
        if line != "":
            _index = 0
            _array = []
            for x in re.split(",|，", line):
                column_name = algorithm.input_field_names[_index]
                _index = _index + 1
                dtype_kind = algorithm.data_source[column_name].dtype.kind
                if dtype_kind == "f":
                    _array.append(float(x))
                elif dtype_kind == "i":
                    _array.append(int(float(x)))
                else:
                    _array.append(x)
            algorithm.predict_input_values.append(_array)
    algorithm.implent()
    algorithm.generateNotebookFile()
    
    if algorithm.algorithm_name == "深度学习-回归":
        context["predict_column_names"] = algorithm.input_field_names + [algorithm.output_field_name]
    else:
        context["predict_column_names"] = algorithm.input_field_names + [algorithm.output_field_name] + ["可能性(%)"]
    
    context["predict_values"] = []
    if algorithm.algorithm_name == "深度学习-二分类":
        for i in range(len(algorithm.predict_input_values)):
            context["predict_values"].append(algorithm.predict_input_values[i] + [algorithm.predict_output_values[i][0]] + [round(algorithm.predict_output_probas[i][0] * 100, 2)])
    elif algorithm.algorithm_name == "深度学习-回归":
        for i in range(len(algorithm.predict_input_values)):
            context["predict_values"].append(algorithm.predict_input_values[i] + [algorithm.predict_output_values[i][0]])
    else:
        for i in range(len(algorithm.predict_input_values)):
            context["predict_values"].append(algorithm.predict_input_values[i] + [algorithm.predict_output_values[i]] + [round(algorithm.predict_output_probas[i][0] * 100, 2)])
    context["algorithm"] = algorithm
    return render(request, "deep_learning/5.html", context)

